﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

namespace Client_Revenue
{
    public partial class ContractItemizedReceipt : System.Web.UI.Page
    {
        #region "Properties & Fields"

        public Decimal InvoiceAmount { get; set; }

        DateTime receivedDated { get; set; }

        private int iClientid
        {
            get
            {
                if (this.ViewState["iClientid"] == null)
                    return 0;

                return (int)this.ViewState["iClientid"];
            }
            set { this.ViewState["iClientid"] = value; }
        }

        private int iCarrierid
        {
            get
            {
                if (this.ViewState["iCarrierid"] == null)
                    return 0;

                return (int)this.ViewState["iCarrierid"];
            }
            set { this.ViewState["iCarrierid"] = value; }
        }

        private string invNum
        {
            get
            {
                if (this.ViewState["invNum"] == null)
                    return string.Empty;

                return this.ViewState["invNum"].ToString();
            }
            set { this.ViewState["invNum"] = value; }
        }

        private int iContractId
        {
            get
            {
                if (this.ViewState["iContractId"] == null)
                    return 0;

                return (int)this.ViewState["iContractId"];
            }
            set { this.ViewState["iContractId"] = value; }
        }

        private Decimal SumOfInv
        {
            get
            {
                if (this.ViewState["SumOfInv"] == null)
                    return Decimal.Zero;

                return (Decimal)this.ViewState["SumOfInv"];

            }
            set { this.ViewState["SumOfInv"] = value; }
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {

            invNum = Request.QueryString["InvNum"];
            // txtItemTotals.Attributes.Add("onFocus", "");


            if (!Page.IsPostBack)
            {
                LoadJScript();
                //InvoiceAmount = TotalCommReceived(invNum);
                lbInvAmount.Text = CarrierInvoiceDetails(invNum).Commission_ReceivedAmt.ToString();
                //lbInvAmount.Text = string.Format("{0:C0}", lbInvAmount.Text);
                lbInvCarrier.Text = InvoiceCarrier(invNum).CarrierName;
                iCarrierid = InvoiceCarrier(invNum).CarrierId;
                lbInvDate.Text = CarrierInvoiceDetails(invNum).ReceiptDate.ToShortDateString();
                lbInvNum.Text = CarrierInvoiceDetails(invNum).QB_InvoiceNum;

                BindData();
            }
        }


        private Decimal TotalCommReceived(string _invnum)
        {
            using (var DE = new dominiumEntities())
            {
                var CommRcvd = (from cc in DE.CarrierCommissions
                                where ((cc.QB_InvoiceNum == _invnum))
                                select cc.Commission_ReceivedAmt).FirstOrDefault();

                return Convert.ToDecimal(CommRcvd);
            }

        }

        private void BindData()
        {
            using (var DE = new dominiumEntities())
            {

                var clientswithContracts = (from c in DE.Clients
                                            join co in DE.Contracts on c.ClientId equals co.ClientId
                                            select new { c.ClientId, c.ClientName }).ToList();

                ddClients.DataSource = clientswithContracts; // DE.Clients.Distinct().ToList();
                ddClients.DataBind();


                rbLineOfBiz.DataSource = DE.LineOfBusinesses.Distinct().ToList();
                rbLineOfBiz.SelectedIndex = 0;
                rbLineOfBiz.DataValueField = "LineOfBusinessId";
                rbLineOfBiz.DataBind();

                rbRevType.DataSource = DE.RevenueTypes.Distinct().ToList();
                rbRevType.SelectedIndex = 0;
                rbRevType.DataBind();


                iClientid = Convert.ToInt32(ddClients.SelectedValue);

                //show any message if necessary
                CheckItemizedInvoiceTotals();
                //Populate Grid for review if available
                setItemizedGridData();

            }
        }

        private Carrier InvoiceCarrier(string _invNum)
        {

            using (var DE = new dominiumEntities())
            {
                return DE.CarrierCommissions.Where(i => i.QB_InvoiceNum == _invNum).Select(c => c.Carrier).FirstOrDefault();
            }

        }

        private CarrierCommission CarrierInvoiceDetails(string _invNum)
        {
            using (var DE = new dominiumEntities())
            {
                return DE.CarrierCommissions.Where(cc => cc.QB_InvoiceNum == _invNum).FirstOrDefault();

            }
        }

        private List<ContractReceipt> ContractInvoiceDetails(string _invNum)
        {
            using (var DE = new dominiumEntities())
            {
                return DE.ContractReceipts.Where(cc => cc.QB_InvoiceNum == _invNum).Distinct().ToList();

            }
        }

        protected void bnAddDetails_Click(object sender, EventArgs e)
        {
            try
            {
                int LoB = Convert.ToInt32(rbLineOfBiz.SelectedValue);

                if (LoB < 1000)
                { LoB = 1000; } //Medical as Default

                using (var DE = new dominiumEntities())
                {
                    if (iClientid >= 1000)
                    {
                        iContractId = DE.Contracts.Where(co => co.ClientId == iClientid).FirstOrDefault().ContractId;
                        if (iContractId >= 1000)
                        {
                            if (SumOfInv < CarrierInvoiceDetails(invNum).Commission_ReceivedAmt)
                            {
                                DE.AddClientContractReceipt(iContractId, iCarrierid, Convert.ToInt32(rbRevType.SelectedValue), LoB, Convert.ToDecimal(txtItemTotals.Text), CarrierInvoiceDetails(invNum).ReceiptDate, txtItemNotes.Text, invNum);
                            }
                            //Show messages
                            CheckItemizedInvoiceTotals();
                            //Populate Grid for review
                            setItemizedGridData();

                            //Allocate Producer payments & Bonus Pooling
                            PayoutSchedule(iContractId, invNum);
                        }
                    }
                    else
                    {
                        lblMessages.Text = "No Contract found for Client: " + DE.Clients.Where(co => co.ClientId == iClientid).FirstOrDefault().ClientName;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void PayoutSchedule(int _contractId, string _InvNum)
        {
            //Add the itemization details to Payout table based on commission set per producer
            //apply bonus pooling where necessary
            try
            {
                using (var DE = new dominiumEntities())
                {
                    List<int> Producers = new List<int>();
                    Producers.AddRange(DE.SalesInfoes.Where(co => co.ContractId == _contractId).Select(p => p.PersonId).ToList());
                    //&& co.SalesRole.RoleName =="Producer"
                    Decimal defPoolComm = 2; //2% Pool
                    Decimal AccruedPool = 0;
                    Decimal BonusAmountPooled = 0;

                    foreach (int id in Producers)
                    {
                        Decimal CommPaid = getNetCommissionToBePaidByContract(_contractId, id);
                        Decimal NetPay = ((DE.ContractReceipts.Where(cr => cr.ContractId == _contractId && cr.QB_InvoiceNum == invNum).Select(cr => cr.ReceivedAmount).SingleOrDefault() * CommPaid)/100);

                        if (CommPaid != 0) // Commission based type only
                        {
                            BonusAmountPooled = ((DE.ContractReceipts.Where(cr => cr.ContractId == _contractId && cr.QB_InvoiceNum == invNum).Select(cr => cr.ReceivedAmount).SingleOrDefault() * defPoolComm) / 100);

                            //Payout
                            DE.AllocateProducerPayOut(id, _contractId, _InvNum, NetPay, CommPaid, DateTime.Today, invNum);

                            // BonusPool 
                            DE.AllocateProducerBonusPool(id, _contractId,_InvNum ,BonusAmountPooled, AccruedPool, defPoolComm, DateTime.Today, invNum);

                        } //May have to include fixed fee types here
                    }
                }

            }
            catch (Exception ex)
            {
                //lblisDone.Text = "Producer payout unsuccessfully";
                throw ex;
            }
        }

        private Decimal getNetCommissionToBePaidByContract(int _contractID, int _producerID)
        {
            using (var DE = new dominiumEntities())
            {
                Decimal ContractComm = DE.SalesInfoes.Where(s => s.PersonId == _producerID && s.ContractId == _contractID).Select(s => s.Commission).SingleOrDefault();
                DateTime ContractStartDate = DE.Contracts.Where(c => c.ContractId == _contractID).Select(s => s.StartDate).FirstOrDefault();
                Decimal NetComm, defPoolComm;

                defPoolComm = 2; //2% Pool

                DateTime dt = DateTime.Today.AddYears(-1);

                if (ContractComm != 0)
                {
                    if (DateTime.Compare(ContractStartDate, dt) >= 1)
                    {
                        NetComm = ContractComm - defPoolComm; // reduce Comm by 2%
                    }
                    else
                    {
                        NetComm = ContractComm;  // 
                    }
                }
                else
                {
                    NetComm = 0;

                }

                return NetComm;
            }
        }

        private void setItemizedGridData()
        {
            using (var DE = new dominiumEntities())
            {

                var itemsAdded = (from cr in DE.ContractReceipts
                                  join co in DE.Contracts on cr.ContractId equals co.ContractId
                                  join c in DE.Clients on co.ClientId equals c.ClientId
                                  where cr.CarrierId == iCarrierid
                                  select new { c.ClientId, c.ClientName, cr.ReceivedAmount, cr.ReceiptDate, cr.ReceiptNotes, LineTotals = "" }).ToList();

                gvItemsReceipt.DataSource = itemsAdded;
                gvItemsReceipt.DataBind();
            }
        }

        private void CheckItemizedInvoiceTotals()
        {
            //check the total from all itemization
            SumOfInv = ContractInvoiceDetails(invNum).Select(a => a.ReceivedAmount).Sum();

            //Reduce Carrier Amount by the added amount
            lbInvAmount.Text = String.Format("{0:C2}", (CarrierInvoiceDetails(invNum).Commission_ReceivedAmt - SumOfInv).ToString("C"));

            if (SumOfInv != 0)
            {
                if (CarrierInvoiceDetails(invNum).Commission_ReceivedAmt < 0)
                {
                    bnAddDetails.Enabled = false;
                    lblMessages.Text = "0.00 balanced reached!";
                }
                else if (SumOfInv >= CarrierInvoiceDetails(invNum).Commission_ReceivedAmt)
                {
                    bnAddDetails.Enabled = false;
                    lblMessages.Text = " Commission Amount reached!";
                }
                else
                {
                    lblMessages.Text = "Total amount used on the Invoice: " + SumOfInv.ToString();
                }
            }

            if (SumOfInv.Equals(CarrierInvoiceDetails(invNum).Commission_ReceivedAmt))
            {
                //set InvoiceAmount is used up flag on
                using (var DE = new dominiumEntities())
                {
                    //TODO
                   // DE.UpdateInvoiceIsItemizedFlag(invNum);
                }

            }
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {

        }

        protected void btnClose_Click(object sender, EventArgs e)
        {

        }

        protected void btShowLineItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        protected void bnCancel_Click(object sender, EventArgs e)
        {

        }

        protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddClients.SelectedIndex != -1)
            {
                iClientid = Convert.ToInt32(ddClients.SelectedValue);

            }
        }
        //load the javascript
        internal void LoadJScript()
        {
            ClientScriptManager script = Page.ClientScript;
            //prevent duplicate script

            if (!script.IsStartupScriptRegistered(this.GetType(), "calc.js"))
            {
                script.RegisterStartupScript(this.GetType(), "calc.js",
                "<script type='text/javascript' src='" + ResolveUrl("~/Scripts/calc.js") + "'></script>");
            }
        }


    }
}
